package com.chukun.concurrency.atomic;

import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 使用AtomicBoolean类，可以保证并发的情况下，被修饰的代码只能被访问一次
 */
@Slf4j
public class AtomicBooleanOperator {

    static AtomicBoolean atomicBoolean = new AtomicBoolean(false);

    //并发线程总数
    private static final int totalThreadCount=1000;

    //允许同时访问的总数
    private static final int allowThreadCount = 200;

    public static void main(String[] args) {

        CountDownLatch countDownLatch = new CountDownLatch(totalThreadCount);
        Semaphore semaphore = new Semaphore(allowThreadCount);
        ExecutorService executorService = Executors.newCachedThreadPool();

        for(int i=0;i<totalThreadCount;i++){
            executorService.execute(()->{
                try {
                    semaphore.acquire();
                    test();
                    semaphore.release();
                }catch (Exception e){
                    log.error("error count add ",e);
                }
                countDownLatch.countDown();
            });
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        executorService.shutdown();
    }

    /**
     * 下面的代码，只会被执行一次
     */
    private  static void test(){
        if(atomicBoolean.compareAndSet(false,true)){
            log.info("execute the code once");
        }
    }
}
